<template>
  <Dialog class="!w-[55%]" :title="dialogTitle" v-model="dialogVisible">
    <el-tabs v-model="activeTab" tab-position="top" @tab-click="">
      <el-tab-pane v-for="(item, index) in panes" :key="item.name" :label="item.label" :name="item.name">
        <el-card v-if="index == 0" shadow="always" :body-style="{ padding: '20px' }">
          <el-card shadow="always" :body-style="{ padding: '20px' }">
            <el-form :disabled="formType == 'audit'" class="searchBar" ref="formRef" :model="formData"
              :rules="formRules" v-loading="formLoading">
              <el-form-item label="客户类别" prop="type">
                <el-select :disabled="formType == 'audit' || formData.status == 1" v-model="formData.type" value-key=""
                  placeholder="请选择" clearable filterable @change="">
                  <el-option v-for="item in customerType_options" :key="item.value" :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <!-- <el-input v-model="formData.name" placeholder="请输入" /> -->
              </el-form-item>
              <el-form-item label="客户名称" prop="name">
                <el-input :disabled="formType == 'audit' || formData.status == 1" v-model="formData.name"
                  placeholder="请输入" />
              </el-form-item>
              <el-form-item label="客户地址" prop="detailAddress">
                <el-input :disabled="formType == 'audit' || formData.status == 1" v-model="formData.detailAddress"
                  placeholder="请输入" />
              </el-form-item>
              <el-form-item label="联系人" prop="contactName">
                <el-input :disabled="formType == 'audit'" v-model="formData.contactName" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="联系人微信" prop="wechat">
                <el-input :disabled="formType == 'audit'" v-model="formData.wechat" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="联系电话" prop="mobile">
                <el-input :disabled="formType == 'audit'" v-model="formData.mobile" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="E-mail" prop="email" class="mr-auto ml-5">
                <el-input :disabled="formType == 'audit'" v-model="formData.email" placeholder="请输入">
                  <!-- <template #append></template> -->
                </el-input>
              </el-form-item>
              <span class="tooltips absolute bottom-43.5 text-[#ccc]">电话、邮件、微信号三者请至少必填一项</span>

            </el-form>
          </el-card>
          <el-card shadow="always" :body-style="{ padding: '20px' }" class=" mt-4">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
              <el-form-item label="负责人" prop="ownerUserName">
                <!-- <el-input v-model="formData.ownerUserName" :disabled="true" placeholder="请输入客户名称" /> -->
                <el-select v-model="formData.ownerUserName" :disabled="!assignFlag">
                  <el-option v-for="item in opt" :key="item" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>

          </el-card>
        </el-card>
        <div v-if="index == 1" class="signFlow">
          <el-card>
            <template #header>
              <div class="card-header">
                <span class="font-[15px] font-700">签核流程</span>
              </div>
            </template>
            <el-table :header-cell-style="{ backgroundColor: '#fafafa' }" :data="flowData" stripe style="width: 100%">
              <el-table-column header-align="center" align="center" type="index" label="序号" width="180" />
              <el-table-column header-align="center" align="center" prop="node" label="节点" />
              <el-table-column header-align="center" align="center" prop="operator" label="操作人" />
              <el-table-column :formatter="handleDate" header-align="center" align="center" prop="createTime"
                label="操作时间" />
              <el-table-column header-align="center" :formatter="getStatusLabel" align="center" prop="status"
                label="签核" />
              <el-table-column header-align="center" align="center" prop="remark" label="签核意见" />
            </el-table>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button v-hasPermi="['quote:customer:audit']" v-if="formType == 'audit'" type="primary" @click="prove"
        :disabled="formLoading">通
        过</el-button>
      <el-button v-hasPermi="['quote:customer:audit']" v-if="formType == 'audit'" type="danger" @click="rejectThis">驳
        回</el-button>
      <el-button
        v-if="formType == 'admin-create' || formType == 'create' || formType == 'reject' || formType == 'assign' || formType == 'update' || formType == 'update-1'"
        @click="submitForm" type="primary" :disabled="formLoading">提 交</el-button>
      <el-button @click="closeModal">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { CustomerApi, CustomerVO } from '@/api/quote/customer'
import { formatDate } from '@/utils/formatTime';
import { useUserStore } from '@/store/modules/user'

/** 客户 表单 */
defineOptions({ name: 'CustomerForm' })
let auditData: any = ref({})
let opt = ref([] as any)
const NoForm = ref({
  remark: [] as any,
  status: [] as any
})
const assignFlag = ref(false)
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const formRef = ref() // 表单 Ref
let flowData: any = ref([])
let activeTab = ref('info')
let panes = ref([
  { label: '客户信息', name: 'info' },
  { label: '签核流程', name: 'flow' },
])
let userInfoStore = useUserStore()
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('客户注册提报') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  ownerUserName: userInfoStore.user.nickname,
  customerType: undefined,
  ownerUserId: userInfoStore.user.id,
  ownerTime: undefined,
  mobile: undefined,
  telephone: undefined,
  qq: undefined,
  wechat: undefined,
  email: undefined,
  areaId: undefined,
  remark: undefined,
  status: undefined,
  type: undefined,
  contactName: undefined,
  detailAddress: undefined
})

const customerType_options = ref([
  { label: '公共客户', value: 2 },
  { label: '外部客户', value: 1 },
])
const formRules = reactive({
  name: [{ required: true, message: '公司名称不能为空', trigger: 'blur' }],
  detailAddress: [{ required: true, message: '公司地址不能为空', trigger: 'blur' }],
  // contactName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  // mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
})

const getStatusLabel = (row: any) => {
  if (row.status == '1') {
    return '同意'
  } else if (row.status == '2') {
    return '驳回'
  } else if (row.status == '0') {
    return '提交'
  }
}

const handleDate = (row: any) => {
  return formatDate(row.createTime)
}

const getFlowData = async (id) => {
  if (id) {
    const res = await CustomerApi.getCustomer(id)
    if (res) {
      flowData.value = res.auditProcessList;
      // 生成对应的v-model
      flowData.value.forEach((f: any) => {
        NoForm.value.status.push({ status: f.status == 0 ? '已提交' : f.status == 1 ? '同意' : '驳回' })
        NoForm.value.remark.push({ remark: f.remark })
      })
    }
  }
}
const closeModal = () => {
  resetForm()
  dialogVisible.value = false
  activeTab.value = 'info'
  // emit('success')
}

//同意
const prove = async () => {
  const data = await message.prompt('请输入审核意见', '通过审核');
  auditData.value.status = '1'
  auditData.value.remark = data.value
  auditData.value.customerId = formData.value.id
  const res = await CustomerApi.auditCustomer(auditData.value)
  if (res) {
    message.success('审核成功，您同意了该次客户审核！')
    dialogVisible.value = false
    emit('success', { status: 0 })
  }
}

const rejectThis = async () => {
  const data = await message.prompt('请输入驳回意见', '驳回审核');
  auditData.value.remark = data.value
  auditData.value.status = '2'
  auditData.value.customerId = formData.value.id
  const res = await CustomerApi.auditCustomer(auditData.value)
  if (res) {
    message.success('审核成功，您驳回了该次客户审核！')
    dialogVisible.value = false
    emit('success', { status: 0 })
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: any, flag?: boolean = false) => {
  formType.value = type
  dialogTitle.value = t('action.' + type)
  dialogVisible.value = true
  if (type == 'create') {
    resetForm()
    assignFlag.value = false
    // 创建允许修改
  } else if (type == 'admin-create') { // 管理员创建
    resetForm()
    assignFlag.value = true
    // 创建允许修改
    dialogTitle.value = '管理员新增'

    //管理员新增 需要可以分配责任人
    const res = await CustomerApi.getOwner();
    if (res) {
      opt.value = [];
      res.list.forEach((item: any) => {
        opt.value.push({ label: item.nickname, value: item.id })
      })
    }
  }
  else {
    if (type == 'assign') {
      const res = await CustomerApi.getOwner();
      if (res) {
        opt.value = [];
        res.list.forEach((item: any) => {
          opt.value.push({ label: item.nickname, value: item.id })
        })
      }
      assignFlag.value = true
    } else {
      assignFlag.value = false
    }
    if (id!.id!) {
      formLoading.value = true
      try {
        formData.value = Object.assign({}, id)
        if (flag) {
          assignFlag.value = true
        }
        // formData.value.ownerUserName = 
      } finally {
        formLoading.value = false
      }
      getFlowData(id!.id!)
      if (id.status == 2) {
        formType.value = 'reject'
        //被驳回的，重新设置类型
      } else if (id.status == 1 && type != 'assign') {
        formType.value = 'update-1'
      }
    } else {
      //新增时，重置表单
      // 表示不允许修改
      assignFlag.value = false
      resetForm()
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (activeTab.value == 'flow') {
    auditData.value.customerId = formData.value.id
    await CustomerApi.auditCustomer(auditData.value)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  }
  if (formType.value == 'admin-create') {
    // 校验表单
    await formRef.value[0].validate()
    // 提交请求
    formLoading.value = true
    try {
      const data = formData.value as unknown as CustomerVO
      const item = opt.value.find((item: any) => item.value == data.ownerUserName)
      if (item) {
        data.ownerUserId = item.value
        data.ownerUserName = item.label
      }
      await CustomerApi.adminCreateCustomer(data)
      message.success(t('common.createSuccess'))
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
    return;
  }
  if (!assignFlag.value && activeTab.value == 'info' && formType.value !== 'create' && formData.value.status != 2) {
    if (formType.value == 'update') {
      const params = {
        ...formData.value
      }
      const res = await CustomerApi.updateCustomer(params as any)
      if (res) {
        message.success(t('common.updateSuccess'))
        dialogVisible.value = false
        // 发送操作成功的事件
        emit('success')
      } else {
        message.error('网络错误！！！请检查')
      }
    } else if (formType.value == 'update-1') {
      //表示通过的单，修改信息
      let res = await CustomerApi.updateCustomer1(formData.value as any)
      if (res) {
        message.success('修改客户信息成功！')
        dialogVisible.value = false
        // 发送操作成功的事件
        emit('success')
      }
    }
    else {
      return;
    }
  }
  if (formType.value == 'create' && activeTab.value == 'info') {
    // 校验表单
    await formRef.value[0].validate()
    // 提交请求
    formLoading.value = true
    try {
      const data = formData.value as unknown as CustomerVO
      await CustomerApi.createCustomer(data)
      message.success(t('common.createSuccess'))
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  } else if (formType.value == 'assign' && activeTab.value == 'info') {
    try {
      formLoading.value = true;
      const data = {
        customerId: formData.value.id,
        ownerId: formData.value.ownerUserName,
      }
      if (isNaN(Number(data.ownerId))) {
        message.info('责任人维持不变！')
        return
      }
      await CustomerApi.changeOwner(data)
      message.success('变换责任人成功！')
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  }
  else if (formType.value == 'reject') { //表示驳回的时候，可以修改在提交
    let res = await CustomerApi.updateCustomer(formData.value as any)
    if (res) {
      message.success('修改客户信息成功！')
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    }
  }

}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    ownerUserName: userInfoStore.user.nickname,
    id: undefined,
    name: undefined,
    customerType: undefined,
    ownerUserId: userInfoStore.user.id,
    ownerTime: undefined,
    mobile: undefined,
    telephone: undefined,
    qq: undefined,
    wechat: undefined,
    email: undefined,
    areaId: undefined,
    remark: undefined,
    status: undefined,
    type: undefined,
    contactName: undefined,
    detailAddress: undefined
  }
  flowData.value = []
}

</script>

<style lang="scss" scoped>
.searchBar {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;

  :deep(.el-form-item) {
    width: 260px !important;
  }
}
</style>
